//
//  WCNPListFileDataStore.m
//  WCN
//
//  Created by 杨鑫 on 15/6/16.
//  Copyright (c) 2015年 ShanghaiCize Trade And Business Co., Ltd. All rights reserved.
//

#import "WCNPListFileDataStore.h"

@interface WCNPListFileDataStore ()

@property (strong, nonatomic) NSString *casePath;
@property (strong, nonatomic) NSString *carePath;
@property (strong, nonatomic) NSString *careWaitForUpload;

@end

@implementation WCNPListFileDataStore

#pragma mark - Create

+ (instancetype)shareStore
{
    static WCNPListFileDataStore *store = nil;
    //block
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        store = [[WCNPListFileDataStore alloc] initPrivate];
    });
    return store;
}

- (instancetype)init
{
    @throw [NSException exceptionWithName:@"Singleton"
                                   reason:@"Use + [WCNPListFileDataStore shareStore]"
                                 userInfo:nil];
    return nil;
}

- (instancetype)initPrivate
{
    self = [super init];
    if (self) {
        _casePath = [self createPath:@"Cases"];
        _carePath = [self createPath:@"Cares"];
        
        _careWaitForUpload = [self createPath:@"CaresWaitForUpload"];
    }
    return self;
}

#pragma mark - Private

- (NSString *)createPath:(NSString *)name
{
    NSFileManager *fm = [NSFileManager defaultManager];
    NSString *path = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:name];
    if (![fm fileExistsAtPath:path isDirectory:nil]) {
        [fm createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
    }
    return path;
}

#pragma mark - Public

- (NSString *)careTemplatePath:(NSString *)fileName
{
    return [self.casePath stringByAppendingPathComponent:fileName];
}

- (NSString *)careRecordPath:(NSString *)fileName
{
    return [self.carePath stringByAppendingPathComponent:fileName];
}

- (NSString *)careUploadPath:(NSString *)fileName
{
    return [self.careWaitForUpload stringByAppendingPathComponent:fileName];
}

- (BOOL)hasFile:(NSString *)path
{
    NSFileManager *fm = [NSFileManager defaultManager];
    if ([fm fileExistsAtPath:path]) {
        return YES;
    }
    return NO;
}

- (NSArray *)readArrayFromFile:(NSString *)path
{
    return [NSArray arrayWithContentsOfFile:path];
}

- (NSDictionary *)readDicFromFile:(NSString *)path
{
    return [NSDictionary dictionaryWithContentsOfFile:path];
}

- (void)saveData:(id)data toFile:(NSString *)path success:(void(^)(void))success
{
    //开启一个异步线程
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        //
        [data writeToFile:path atomically:YES];
        //同步到主线程
        dispatch_async(dispatch_get_main_queue(), ^{
            success?success():nil;
        });
    });
}

- (NSArray *)saveCareRecords:(NSArray *)records toFile:(NSString *)path success:(void(^)(void))success
{
    NSMutableArray *muArray = [NSMutableArray array];
    if (records.count >1) {
        NSMutableArray *muItemArray = [NSMutableArray array];
        [muItemArray addObject:records[0]];
        for (int i=1; i<records.count; i++) {
            NSDictionary *item1 = records[i-1], *item2 = records[i];
            if ([item1[@"targetDay"] intValue] == [item2[@"targetDay"] intValue]) {
                [muItemArray addObject:item2];
            } else {
                [muArray addObject:muItemArray];
                muItemArray = [NSMutableArray array];
                [muItemArray addObject:item2];
            }
        }
        [muArray addObject:muItemArray];
        [self saveData:muArray toFile:path success:success];
    } else if (records.count == 1) {
        [muArray addObject:@[records[0]]];
        [self saveData:muArray toFile:path success:success];
    } else {
        success?success():nil;
    }
    
    return muArray;
}

- (void)deletePrivateFiles
{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSFileManager *fm = [NSFileManager defaultManager];
        [fm removeItemAtPath:self.carePath error:nil];
        
        self.carePath = [self createPath:@"Cares"];
    });
}

- (void)deleteFiles
{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSFileManager *fm = [NSFileManager defaultManager];
        [fm removeItemAtPath:self.carePath error:nil];
        [fm removeItemAtPath:self.casePath error:nil];
        
        self.carePath = [self createPath:@"Cares"];
        self.casePath = [self createPath:@"Cases"];
    });
}

- (void)deleteCacheCaresAfterUpload:(NSString *)path
{
//    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
//    });
}

@end
